import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux'
import {fetchPatient,fetchUserImage,updateImage,changePage ,mPacs,removeImage} from '../../store/actions';
import {message,Card, Col, Row,Button,Tag,Modal,Form,Input} from 'antd';

const FormItem = Form.Item;

require('../../../css/label-list.css');

class _ExamineDetail extends React.Component{
    constructor(props){
        super(props);
        this.state= {
            image:{},
            patient:{},
            modal:{
                title:'',
                text:'',
                visible:false
            },
            modalDel:{
                title:'',
                text:'',
                visible:false
            },
            user:this.props.user
        };
        this.pass = this.pass.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.handleOk = this.handleOk.bind(this);
        this.handleReject = this.handleReject.bind(this);
        this.viewImage = this.viewImage.bind(this);
        this.deleteImage = this.deleteImage.bind(this);
        this.handleOkDel = this.handleOkDel.bind(this);
        this.handleCancelDel = this.handleCancelDel.bind(this);
        this.imageOperate = this.imageOperate.bind(this);
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    changePage(){
        this.props.dispatch(changePage('examine'));
    }
    handleOkDel(){
        const _this = this,
            studyId = _this.state.image.id;
        _this.setState({
            modalDel: {
                confirmLoading: true,
                visible:true,
                text:'您确认要删除这个影像吗？',
                title:'删除影像'
            }
        },function(){
            _this.props.dispatch(removeImage(studyId,function(){
                message.success('删除影像成功',1,function(){
                    _this.setState({
                        modalDel: {
                            confirmLoading: false,
                            visible:false,
                            text:'',
                            title:''
                        }
                    },function(){
                        _this.context.router.push('/images')
                    })
                })
            }))
        });
    }
    handleCancelDel(){
        this.setState({
            modalDel:{
                visible:false
            }
        })
    }
    deleteImage(){
        const name = this.state.image.name !== ''?this.state.image.name :'佚名',
            check = this.state.image.check_item_name;
        this.setState({
            modalDel:{
                visible:true,
                text:`您确认要删除 ${name} 的 ${check} 影像吗？`,
                title:'删除影像'
            }
        });
    }
    pass(e){
        e.preventDefault();
        const name = e.target.name;
        this.setState({
            modal:{
                visible:true,
                text:`您正在审核 ${name} 影像`,
                title:'审核影像'
            }
        });
    }
    handleOk(e){
        e.preventDefault();
        const _this = this,
            studyId = _this.props.params.id;
        _this.setState({
            modal:{
                confirmLoading: true,
                visible:true,
                text:_this.state.modal.text,
                title:_this.state.modal.title,
                type:false
            }
        },function(){
            const sendData = Object.assign({},{id:studyId,status:2},_this.props.form.getFieldsValue());
            _this.props.dispatch(updateImage(sendData,function(){
                message.success('影像通过审核',1,function(){
                    _this.setState({
                        modal: {
                            confirmLoading: false,
                            visible:false,
                            text:'',
                            title:'',
                            pid:''
                        }
                    },function(){
                        try{
                            _this.props.dispatch(fetchUserImage(studyId,function(res){
                                const image = res.content,
                                    pid = image.pid;
                                _this.props.dispatch(fetchPatient(pid,function(res){
                                    const newState = {
                                        image,
                                        patient: res.content
                                    };
                                    _this.setState({...newState})
                                }));
                            },function(){
                                message.error('影像获取失败',1,function(){
                                    _this.context.router.push('/examine')
                                })
                            }));
                        }catch(e){}

                    })
                });
            },function(res){
                message.error(`出错了！！${res.head.msg}`,1)
            }))
        });
    }
    handleReject(e){
        e.preventDefault();
        const _this = this,
            studyId = _this.props.params.id;
        _this.setState({
            modal:{
                confirmLoading: true,
                visible:true,
                text:_this.state.modal.text,
                title:_this.state.modal.title,
                type:true
            }
        },function(){
            const memo = this.props.form.getFieldsValue().memo;
            if(!!memo){
                const sendData = Object.assign({},{id:studyId,status:(-2)},_this.props.form.getFieldsValue());
                _this.props.dispatch(updateImage(sendData,function(){
                    message.success('影像通过审核',1,function(){
                        _this.setState({
                            modal: {
                                confirmLoading: false,
                                visible:false,
                                text:'',
                                title:'',
                                pid:''
                            }
                        },function(){
                            try{
                                _this.props.dispatch(fetchUserImage(studyId,function(res){
                                    const image = res.content,
                                        pid = image.pid;
                                    _this.props.dispatch(fetchPatient(pid,function(res){
                                        const newState = {
                                            image,
                                            patient: res.content
                                        };
                                        _this.setState({...newState})
                                    }));
                                }));
                            }catch(e){}
                        })
                    });
                },function(res){
                    message.error(`出错了！！${res.head.msg}`,1)
                }))
            }else{
                message.warning('审核不通过时需要填写拒绝理由',2);
                return
            }
        });
    }
    handleCancel(){
        this.setState({
            modal:{
                visible:false
            }
        })
    }
    viewImage(){
        if(!!this.state.image.study_instance_uid){
            this.props.dispatch(mPacs(this.state.image.study_instance_uid,function(url){
                window.open(
                    url,
                    'viewer',
                    'location=no,toolbar=no,alwaysRaised=yes,screenX=0,screenY=0'
                );
            }))
        }else{
            message.warning('影像还没有准备好')
        }
    }
    componentWillMount(){
        const _this= this,
          studyId = _this.props.params.id;
        try{
            _this.props.dispatch(fetchUserImage(studyId,function(res){
                const image = res.content,
                        pid = image.pid;
                _this.props.dispatch(fetchPatient(pid,function(res){
                    const newState = {
                        image,
                        patient: res.content
                    };
                    _this.setState({...newState})
                }));
            },function(res){
                const _msg = res.head.msg,
                    cause = /accessToken/.test(_msg);
                if(cause){
                    message.error('您的账户已过期，请重新登录',1);
                    _this.context.router.push('/login');
                }else{
                    message.error('获取影像失败',1)
                }
            }));
        }catch(e){}
    }

    imageOperate(status,name,check){
        switch (status){
            case -2:
            case 2:
                return (
                    <div>
                        <Button type="primary" icon="eye" size="large" onClick={this.viewImage}>查看影像</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <Button type="ghost" icon="delete" size="small" onClick={this.deleteImage}>删除</Button>
                    </div>
                );
            case -1:
            case 0:
                return (
                    <div>
                        <Button type="ghost" icon="delete" onClick={this.deleteImage}>删除</Button>
                    </div>
                );
            case 1:
                return (
                    <div>
                        <Button type="primary" icon="edit" size="large" name={`${name}的${check}`} onClick={this.pass}>审核</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <Button type="primary" icon="eye" size="large" onClick={this.viewImage}>查看影像</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <Button type="ghost" icon="delete" size="small" onClick={this.deleteImage}>删除</Button>
                    </div>
                );
            default:
                return '未知状态，拒绝显示数据，请联系管理员！'

        }
    }


    render(){
        const footBtn = this.imageOperate(this.state.image.status,this.state.image.name,this.state.image.check_item_name);
        const { getFieldProps } = this.props.form;

        const memoProps = getFieldProps('memo', {
            rules: [
                { required: this.state.modal.type, message: this.state.modal.msg }
            ]
        });
        return(
            <div style={{ background: '', padding: '10px' }}>

                {/**
                * image.statue:
                * -2 => 审核不通过
                * -1 => 到入出错
                * 0 => 未导入
                * 1 => 已导入，未审核
                * 2 => 审核通过
                * */}

                <Row justify="space-around" align="top">
                    <Col xs={{span:11}}
                         sm={{span:11}}
                         md={{span:10}}
                         lg={{span:10}}
                    >
                        <Card title={`影像信息`} bordered={false}>
                            <ul className="label-list">
                                <li><label>来源</label>{this.state.image.origin || `个人上传`} </li>
                                <li><label>设备类型</label>{this.state.image.modality || `--`} </li>
                                <li><label>检查部位</label>{this.state.image.bodypart || `--`} </li>
                                <li><label>检查项目</label>{this.state.image.check_item_name || `--`} </li>
                                <li><label>检查费用</label>{this.state.image.cost || `--`} </li>
                                <li><label>检查日期</label>{this.state.image.studydate || `--`} </li>
                                <li><label>检查时年龄</label>{this.state.image.patientage || `--`} </li>
                                <li><label>影像号</label>{this.state.image.study_instance_uid || `--`} </li>
                                <li><label>检查号</label>{this.state.image.check_code || `--`} </li>
                                <li><label>检查机构</label>{this.state.image.institution || `--`} </li>
                                <li><label>设备品牌</label>{this.state.image.modality_brand || `--`} </li>
                                <li><label>设备型号</label>{this.state.image.modality_type || `--`} </li>
                                <li><label>导入时间</label>{this.state.image.importdate || '--'}</li>
                                {this.state.image.status == -2?<li><label>拒绝理由</label>{this.state.image.memo}</li>:''}
                                {this.state.image.status == -1?<li><label>失败原因</label>{this.state.image.memo}</li>:''}

                            </ul>
                            {footBtn}
                        </Card>
                        <Card title={`病症信息`} bordered={false}>
                            <ul className="label-list">
                                <li><label>临床诊断</label>{this.state.image.diagnosis || `--`} </li>
                                <li><label>症状描述</label>{this.state.image.symptom || `--`} </li>
                                <li><label>过往病史</label>{this.state.patient.history || `--`} </li>
                            </ul>
                        </Card>
                    </Col>
                    <Col xs={{span:11,offset:1}}
                         sm={{span:11,offset:1}}
                         md={{span:10,offset:1}}
                         lg={{span:10,offset:1}}
                    >
                        <Card title={`基本信息`} bordered={false}>
                            <ul className="label-list">
                                <li><label>姓名</label>{this.state.patient.name || `佚名`} </li>
                                <li><label>性别</label>{`${this.state.patient.gender}`==`M`?`男`:`女`} </li>
                                <li><label>生日</label>{this.state.patient.birthday || `--`} </li>
                                <li><label>年龄</label>{this.state.patient.age || `--`} </li>
                                <li><label>身份证</label>{this.state.patient.idcard || `--`} </li>
                                <li><label>社保号</label>{this.state.patient.sbh || `--`} </li>
                                <li><label>联系方式</label>{this.state.patient.mobile || `--`} </li>
                                <li><label>地址</label>{this.state.patient.address || `--`} </li>
                                <li><label>关系</label>{this.state.patient.relationship ||`--`} </li>
                                <li><label>状态</label>{this.state.patient.status == 0? <Tag color="">已删除</Tag>:<Tag color="green">正常</Tag>}</li>
                            </ul>
                        </Card>
                        <br />
                    </Col>
                </Row>

                {`${this.state.image.status}`==1?<Modal title={this.state.modal.title}
                       visible={this.state.modal.visible}
                       confirmLoading={this.state.modal.confirmLoading}
                       onCancel={this.handleCancel}
                       footer={[
                            <Button key="ok" type="primary" size="large" onClick={this.handleOk}>
                                审核通过
                            </Button>,
                            <Button key="reject" type="" size="large" onClick={this.handleReject}>
                                驳回
                            </Button>,
                            <Button key="back" type="ghost" size="large" onClick={this.handleCancel}>
                                取消
                            </Button>
                        ]}
                >
                    <p>{this.state.modal.text}</p>
                    <Form>
                        <FormItem
                            help="请注明审核结果的原因"
                        >
                            <Input
                                {...memoProps}
                                type="textarea" placeholder="请注明审核结果的原因" />
                        </FormItem>
                    </Form>
                </Modal>:''}
                <Modal title={this.state.modalDel.title}
                       visible={this.state.modalDel.visible}
                       onOk={this.handleOkDel}
                       confirmLoading={this.state.modalDel.confirmLoading}
                       onCancel={this.handleCancelDel}
                >
                    <p>{this.state.modalDel.text}</p>
                </Modal>
            </div>
        )
    }
}

_ExamineDetail = Form.create()(_ExamineDetail);
/**
 * @#$注意：
 * 初步加载时fetch了数据，
 * 后面还使用connect关联store中的数据，
 * 这是重复的，以后根据数据缓存策略再作调整
 * */

const ExamineDetail = connect((state)=>{
    const {user} = state.rootReducer;
    const {patients} = state.rootReducer.patients.items;
    const {images} = state.rootReducer.images.items;
    return {user,patients,images}
})(_ExamineDetail);
export default ExamineDetail;